package com.lb.interceptor;
import com.alibaba.fastjson.JSONObject;
import com.lb.common.BaseContext;
import com.lb.common.Result;
import com.lb.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;

@Component
public class UserLoginCheckinterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getRequestURL().toString();
        // log.info("请求的url为:%s",url);
        //获取请求url中是否包含login,如果包含，说明是登陆操作，放行
        if (url.contains("login")) {
            System.out.println("放行");
            //  filterChain.doFilter(servletRequest, servletResponse);
            //   chain.doFilter(request,response);
            return true;
        }
        //获取请求中的令牌（token）
        String jwt = request.getHeader("Authorization");
        //判断令牌是否存在
        if (!StringUtils.hasLength(jwt)) {
            Result error = Result.error("请求头为空");
            String notlogin = JSONObject.toJSONString(error);
            response.getWriter().write(notlogin);
            // log.info("jwt为空");
            return false;
        }
        //解析token如果解析失败，返回错误结果
        try {
            Map<String,Object> claims =JwtUtils.parseJWT(jwt);
            // Long userId = Long.valueOf(claims.get(JwtClaimsConstant.USER_ID).toString());
            Long id = Long.valueOf(claims.get("id").toString());
            BaseContext.setCurrentId(id);
        } catch (Exception e) {
            e.printStackTrace();
            Result error = Result.error("请求头为空");
            String notlogin = JSONObject.toJSONString(error);
            //  log.info("jwt解析错误");
            response.getWriter().write(notlogin);
            return false;
        }
        return true;
        //放行
        //  filterChain.doFilter(servletRequest, servletResponse);
        //  log.info("令牌tong过，放行");
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}

